/**
 * 
 */
package edu.fjnu.hotelsys.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import edu.fjnu.hotelsys.domain.Room;
import edu.fjnu.hotelsys.utils.DBUtils;

/**
 * @author Administrator
 *
 */
public class RoomDaoJDBCImpl implements RoomDao {
	
	private static final String ADD_ROOM="insert into room values(seq_room.nextval,?,?,?,?,?,?)";
	private static final String LOAD_ALL="select * from room order by room_id desc";

	/* (non-Javadoc)
	 * @see edu.fjnu.hotelsys.dao.RoomDao#add(edu.fjnu.hotelsys.domain.Room)
	 */
    public void add(Room room) {
		
		Connection conn=DBUtils.getInstance().getConn();
		PreparedStatement pstmt=null;
		
		try {
		  pstmt=conn.prepareStatement(ADD_ROOM);
		  pstmt.setString(1,room.getRoomNo());
		  pstmt.setString(2,room.getRoomType());
		  
		  StringBuffer sb=new StringBuffer();
		  for(String equip:room.getRoomEquip())
		     sb.append(equip).append("|");
		  if(sb.length()>0) sb.deleteCharAt(sb.length()-1);
		  
		  pstmt.setString(3,sb.toString());
		  pstmt.setString(4, room.getRoomStatus());
		  pstmt.setString(5, room.getRoomMemo());
		  pstmt.setInt(6, room.getHotel().getHotelNo());
		  pstmt.executeUpdate();
		  
 		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
		   DBUtils.getInstance().ReleaseRes(conn, pstmt, null);
		}
    }

	public List<Room> loadRoom() {
		
		Connection conn=DBUtils.getInstance().getConn();
		PreparedStatement pstmt=null;
		ResultSet rset=null;
		List<Room> roomList=null;
		
		try {
			pstmt=conn.prepareStatement(LOAD_ALL);
			rset=pstmt.executeQuery();
			HotelDao hotelDao=new HotelDaoJDBCImpl();
			roomList=new ArrayList<Room>();
			while(rset.next()){
				Room room=new Room();
				room.setRoomId(rset.getInt("room_id"));
				room.setRoomNo(rset.getString("room_no"));
				room.setRoomEquip(rset.getString("room_equip").split("\\|"));
				room.setRoomMemo(rset.getString("room_memo"));
				room.setRoomType(rset.getString("room_type"));
				room.setRoomStatus(rset.getString("room_status"));
				room.setHotel(hotelDao.getHotelByNo(rset.getInt("hotel_no")));
			    roomList.add(room);
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return roomList;
	}
}
